package com.geovis.boot.service;

import cn.hutool.core.util.StrUtil;
import com.geovis.boot.common.dto.Result;
import com.geovis.boot.common.util.ResponseUtil;
import com.geovis.boot.gen.util.MPGen;
import com.geovis.boot.gen.util.MpGenConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.stream.Stream;

@Slf4j
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class GbServiceGenStarter {
    public static void main(String[] args) {
        SpringApplication.run(GbServiceGenStarter.class, args);
    }

    @RestController
    class EchoController {
        @RequestMapping(value = "/echo/{a}")
        public String echo(@PathVariable("a") String a) {
            return a;
        }

    }

    @Controller
    class GenController {
        //目录修改为通用目录
        private String genPath = System.getProperty("java.io.tmpdir");

        @RequestMapping(value = {"/", "/genCode"})
        public String index(){
            return "forward:/index.html";
        }

        @RequestMapping(value = "/gen")
        public void gen(HttpServletResponse response, @ModelAttribute MpGenConfig mpGenConfig, @ModelAttribute TablesVO tables) throws IOException {

            if(StrUtil.isBlank(tables.getTables())){
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "表名不能为空"));
                return;
            }
            Result genResult;
            String genPath2;
            try {
                genPath2 = genPath + File.separator + System.currentTimeMillis();
                log.info("genPath2: {}", genPath2);
                genResult = MPGen.gen(mpGenConfig, tables.getTables().split(","), genPath2);
                if(genResult.getCode() != 200){
                    ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, genResult.getMessage()));
                    return;
                }
            } catch (Exception e) {
                ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, e.getMessage()));
                return;
            }
            File zip = new File(genResult.getResult().toString());
            ServletOutputStream out = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/zip");
            out = response.getOutputStream();
            InputStream is = new FileInputStream(zip);
            int len = 0;
            byte[] b = new byte[1024];
            while((len = is.read(b)) != -1){
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            is.close();
            //删除文件夹和压缩文件
            delFile(genPath2);
            delFile(genResult.getResult().toString());
            //todo 生成vue
        }
    }

    private void delFile(String pathStr) throws IOException {
        Path path = Paths.get(pathStr);

        try (Stream<Path> walk = Files.walk(path)) {
            walk.sorted(Comparator.reverseOrder())
                    .forEach(GbServiceGenStarter::deleteDirectoryStream);
        }

    }

    private static void deleteDirectoryStream(Path path) {
        try {
            Files.delete(path);
            log.info("删除文件成功：{}",path.toString());
        } catch (IOException e) {
            log.error("无法删除的路径 {}", path);
        }
    }

    @Data
    class TablesVO {
        private String tables;
    }
}
